<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="客户姓名" prop="realName">
        <el-input v-model="queryParams.realName" placeholder="客户姓名" clearable size="mini"
                  @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="客户手机号" prop="phone">
        <el-input v-model="queryParams.phone" placeholder="客户手机号" clearable size="mini"
                  @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="汽车品牌" prop="brand">
        <el-select v-model="queryParams.brand" filterable placeholder="汽车品牌" clearable size="mini">
          <el-option v-for="dict in brandOptions" :key="dict.value" :label="dict.label" :value="+dict.value"/>
        </el-select>
      </el-form-item>
      <el-form-item label="汽车型号" prop="model">
        <el-input v-model="queryParams.model" placeholder="汽车型号" clearable size="mini"
                  @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="汽车颜色" prop="color">
        <el-input v-model="queryParams.color" placeholder="汽车颜色" clearable size="mini"
                  @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="车架号" prop="frameNo">
        <el-input v-model="queryParams.frameNo" placeholder="车架编号" clearable size="mini"
                  @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="发动机号" prop="engineNo">
        <el-input v-model="queryParams.engineNo" placeholder="发动机号" clearable size="mini"
                  @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker v-model="dateRange" size="mini" style="width: 240px" value-format="yyyy-MM-dd" type="daterange"
                        range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd"
                   v-hasPerm="['beauty:vehicle:add']">
          新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
                   v-hasPerm="['beauty:vehicle:edit']">修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
                   v-hasPerm="['beauty:vehicle:remove']">删除
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="vehicleList" @selection-change="handleSelectionChange" :height="tableHeight">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column type="expand">
        <template slot-scope="scope">
          <el-form label-position="left" inline class="demo-table-expand">
            <el-form-item label="客户姓名">
              <span>{{ scope.row.member.realName }}</span>
            </el-form-item>
            <el-form-item label="客户手机号">
              <span>{{ scope.row.member.phone }}</span>
            </el-form-item>
            <el-form-item label="车架号">
              <span>{{ scope.row.frameNo }}</span>
            </el-form-item>
            <el-form-item label="发动机号">
              <span>{{ scope.row.engineNo }}</span>
            </el-form-item>
            <el-form-item label="年检时间">
              <span>{{ scope.row.inspectionTime }}</span>
            </el-form-item>
            <el-form-item label="保险时间">
              <span>{{ scope.row.insuranceStartTime }}~{{ scope.row.insuranceEndTime }}</span>
            </el-form-item>
          </el-form>
        </template>
      </el-table-column>
      <el-table-column label="序号" type="index" width="50" align="center"/>
      <el-table-column label="汽车图片" align="center" prop="pic" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <span v-if="scope.row.pic==''">暂无</span>
          <el-image v-else :src="scope.row.pic" style="width: 40px; height: 40px" fit="fill"
                    :preview-src-list="[scope.row.pic]"/>
        </template>
      </el-table-column>
      <el-table-column label="车牌号" align="center" prop="licenseNumber" :show-overflow-tooltip="true"/>
      <el-table-column label="汽车品牌" align="center" prop="brand" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <span v-if="brandFormat(scope.row)==''">暂无</span>
          <el-image v-else :src="brandFormat(scope.row)" style="width: 40px; height: 40px" fit="fill"
                    :preview-src-list="[brandFormat(scope.row)]"/>
        </template>
      </el-table-column>
      <el-table-column label="型号" align="center" prop="model" :show-overflow-tooltip="true"/>
      <el-table-column label="汽车颜色" align="center" prop="color" :show-overflow-tooltip="true"/>
      <el-table-column label="创建时间" align="center" prop="gmtCreate" width="100">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.gmtCreate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                     v-hasPerm="['beauty:vehicle:edit']">修改
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                     v-hasPerm="['beauty:vehicle:remove']">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.current" :limit.sync="queryParams.size"
                @pagination="getList"/>

    <!-- 添加或修改公告对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="780px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="客户" prop="memberId">
              <el-select v-model="form.memberId" filterable clearable placeholder="请选择客户"
                         :disabled="form.memberId!=undefined">
                <el-option v-for="item in memberOptions" :key="item.id" :label="`${item.realName}--${item.phone}`"
                           :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="车牌号" prop="licenseNumber">
              <el-input v-model="form.licenseNumber" placeholder="请输入车牌号(如沪A88888)" minlength="7" maxlength="7"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-form-item label="汽车图片" prop="pic">
            <el-upload class="up-img-uploader" :action="imageAction" :show-file-list="false"
                       :on-success="handleUploadSuccess" :headers="headers">
              <img v-if="imageUrl" :src="imageUrl" class="up-img" alt="">
              <i v-else class="el-icon-plus avatar-uploader-icon"/>
            </el-upload>
          </el-form-item>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="品牌" prop="brand">
              <el-select v-model="form.brand" placeholder="请选择">
                <el-option v-for="dict in brandOptions" :key="dict.value" :label="dict.label"
                           :value="+dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="型号" prop="model">
              <el-input v-model="form.model" placeholder="请输入型号(如CA7200)"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="颜色" prop="color">
              <el-input v-model="form.color" placeholder="请输入汽车颜色(如红色)"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="车架号" prop="frameNo">
              <el-input v-model="form.frameNo" placeholder="请输入车架号(如LTVBJ222360014063)" minlength="17"
                        maxlength="17"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="发动机号" prop="engineNo">
              <el-input v-model="form.engineNo" placeholder="请输入发动机号(如JK1233az)" minlength="7" maxlength="8"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="年检日期">
              <el-date-picker v-model="form.inspectionTime" type="date"
                              placeholder="选择年检日期"></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="保险时间">
              <el-date-picker v-model="insuranceDateRange" size="mini" value-format="yyyy-MM-dd" type="daterange"
                              range-separator="-" start-placeholder="保险开始日期" end-placeholder="保险到期日期"
                              @change="insuranceDateRangeChange"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getVehicle, updateVehicle, addVehicle, delVehicle } from '@a/beauty/vehicle'
import { listVehicle } from '@a/beauty/vehicle'
import { getMemberOptionSelect } from '@a/beauty/member'
import { getToken } from '@u/auth'

export default {
  name: 'vehicle',
  data() {
    return {
      // 保险时间
      insuranceDateRange: [],
      imageUrl: null, // 上传图片回显
      headers: {
        // 上传文件的请求头
        Authorization: 'Bearer ' + getToken()
      },
      // 请求地址
      imageAction: process.env.VUE_APP_BASE_API + process.env.VUE_APP_FILE_UPLOAD, // 上传的图片服务器地址
      tableHeight: window.innerHeight - 340,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 表格数据
      vehicleList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 品牌数据字典
      brandOptions: [],
      // 日期范围
      dateRange: [],
      // 查询参数
      queryParams: {
        current: 1,
        size: 10,
        brand: undefined,
        licenseNumber: undefined,
        model: undefined,
        color: undefined,
        frameNo: undefined,
        engineNo: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        memberId: [
          { required: true, message: '客户信息不能为空', trigger: 'blur' }
        ],
        licenseNumber: [
          { required: true, message: '车牌号不能为空', trigger: 'blur' },
          {
            pattern: /^([京津晋冀蒙辽吉黑沪苏浙皖闽赣鲁豫鄂湘粤桂琼渝川贵云藏陕甘青宁新][ABCDEFGHJKLMNPQRSTUVWXY][1-9DF][1-9ABCDEFGHJKLMNPQRSTUVWXYZ]\d{3}[1-9DF]|[京津晋冀蒙辽吉黑沪苏浙皖闽赣鲁豫鄂湘粤桂琼渝川贵云藏陕甘青宁新][ABCDEFGHJKLMNPQRSTUVWXY][\dABCDEFGHJKLNMxPQRSTUVWXYZ]{5})$/,
            message: '车牌号不合法',
            trigger: 'blur'
          }
        ],
        pic: [
          { required: true, message: '汽车图片不能为空', trigger: 'blur' }
        ],
        brand: [
          { required: true, message: '汽车品牌不能为空', trigger: 'blur' }
        ],
        model: [
          { required: true, message: '汽车型号不能为空', trigger: 'blur' }
        ],
        color: [
          { required: true, message: '汽车颜色不能为空', trigger: 'blur' }
        ],
        frameNo: [
          { required: true, message: '车架号不能为空', trigger: 'blur' },
          { pattern: /^[A-HJ-NPR-Z\d]{17}$/, message: '车架编号不合法', trigger: 'blur' }
        ],
        engineNo: [
          { required: true, message: '发动机号不能为空', trigger: 'blur' },
          { pattern: /^[\da-zA-Z]{7,8}$/, message: '发动机号不合法', trigger: 'blur' }
        ]
      },
      // 客户列表 id phone
      memberOptions: []
    }
  },
  created() {
    this.getList()
    this.getDictItems('beauty_vehicle_brand').then(response => {
      this.brandOptions = response.data
    })
    this.getMemberOptions()
  },
  methods: {
    insuranceDateRangeChange(val) {
      console.log(val)
      if (null != val && '' != val) {
        this.form.insuranceStartTime = val[0]
        this.form.insuranceEndTime = val[1]
        // console.log(this.form)
      }
    },
    /** 上传封面成功 **/
    handleUploadSuccess(res, file) {
      // console.log(res)
      if (res.code == 200) {
        const { url } = res.data
        this.msgNoticeSuccess('上传成功')
        console.log(url)
        this.imageUrl = url
        this.form.pic = url
      }
    },
    getMemberOptions() {
      getMemberOptionSelect().then(res => {
        this.memberOptions = res.data
      })
    },
    /** 查询列表 */
    getList() {
      this.loading = true
      listVehicle(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.vehicleList = response.data.records
        this.total = response.data.total
        this.loading = false
      })
    },
    // 状态字典翻译
    brandFormat(row, column) {
      return this.selectDictImg(this.brandOptions, row.brand)
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        memberId: undefined,
        brand: undefined,
        licenseNumber: undefined,
        pic: undefined,
        color: undefined,
        model: undefined,
        inspectionTime: undefined,
        insuranceStartTime: undefined,
        insuranceEndTime: undefined,
        frameNo: undefined,
        engineNo: undefined
      }
      this.imageUrl = null
      this.insuranceDateRange = []
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.current = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length != 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加车辆'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getVehicle(id).then(response => {
        this.form = response.data
        // 回显图片
        this.imageUrl = this.form.pic
        const { insuranceStartTime, insuranceEndTime } = response.data
        if (insuranceStartTime != undefined && insuranceEndTime != undefined) {
          this.insuranceDateRange = [insuranceStartTime, insuranceEndTime]
        }
        this.open = true
        this.title = '修改车辆'
      })
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.id != undefined) {
            updateVehicle(this.form).then(response => {
              this.msgNoticeSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            addVehicle(this.form).then(response => {
              this.msgNoticeSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$confirm('是否确认删除车辆编号为"' + ids + '"的数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return delVehicle(ids)
      }).then(() => {
        this.getList()
        this.msgNoticeSuccess('删除成功')
      })
    }
  }
}
</script>
<style scoped>
.demo-table-expand {
  font-size: 0;
}

.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}

.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 50%;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.up-img-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #000000;
  background-color: #e8e8e8;
  width: 170px;
  height: 170px;
  line-height: 170px;
  text-align: center;
}

.up-img {
  width: 170px;
  height: 170px;
  display: block;
}

</style>
